from django.shortcuts import render

# Create your views here.
from excel_response import ExcelResponse
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework_simplejwt.authentication import JWTAuthentication

from main.models import OverworkSignup
from main.serializers import OverworkSignupSerializer, OverworkSignupWithRawDatetimeSerializer, \
    OverworkSignupExportSerializer


class OverworkSignupViewSet(ModelViewSet):
    queryset = OverworkSignup.objects.all()
    serializer_class = OverworkSignupSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JWTAuthentication,)

    def get_queryset(self):
        if self.action == 'list':
            return super().get_queryset().filter(user=self.request.user)

        return super().get_queryset()

    def get_permissions(self):
        if self.action == 'export':
            return []
        else:
            return super().get_permissions()

    def get_serializer_class(self):
        if self.action == 'retrieve' and self.request.query_params.get('raw_datetime'):
            return OverworkSignupWithRawDatetimeSerializer
        elif self.action == 'export':
            return OverworkSignupExportSerializer
        else:
            return super().get_serializer_class()

    @action(methods=['GET'], detail=False)
    def export(self, request, *args, **kwargs):
        work_start_at_start = request.query_params.get('work_start_at')
        work_start_at_end = request.query_params.get('work_end_at')
        kwargs = {}
        if all([work_start_at_start, work_start_at_end]):
            kwargs = dict(work_start_at__range=(work_start_at_start, work_start_at_end))
        objs = OverworkSignup.objects.filter(**kwargs)
        serializer = self.get_serializer(objs, many=True)
        return ExcelResponse(serializer.data)

